package org.squabble.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.squabble.domain.Account;
import org.squabble.service.AccountService;
import org.squabble.web.AbstractPasswordRequiredCommand;


@Component(value="passwordRequiredValidator")
public class PasswordRequiredValidator implements Validator {

	@Autowired
	PasswordEncoder passwordEncoder;
	
	@Autowired
	AccountService accountService;

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return AbstractPasswordRequiredCommand.class.isAssignableFrom(clazz);
	}

	
	
	@Override
	public void validate(Object arg0, Errors errors) {
		AbstractPasswordRequiredCommand aprc = (AbstractPasswordRequiredCommand) arg0;
		Account account = accountService.getAccount(aprc.getAccountId());
		boolean valid = passwordEncoder.isPasswordValid(account.getPassword(), aprc.getCurrentPassword(), account.getSalt());
		if(!valid) {
			errors.rejectValue("currentPassword", "AbstractPasswordRequiredCommand.currentPassword[invalid]");
		}
	}
}
